﻿using System;
using System.Text;
using System.IO;
using System.IO.Packaging;

using xEngine.UI;
using xEngine.Debugging;

using Microsoft.Xna.Framework.Graphics;

namespace xEngine.Utils
{
    public static class DataLoader
    {
        private static XRenderer _renderer = null;

        public static void Initialize(XRenderer renderer)
        {
            _renderer = renderer;
        }

        public static Stream GetStream(string uri)
        {
            //LogWriter.WriteLine = "GetStream(" + uri + ")";
            return File.Exists(uri) ? ReadStream(uri) : UnpackStream(uri);
        }

        public static string GetStreamAsText(string uri)
        {
            Stream s = GetStream(uri);

            if (s == null)
                return string.Empty;

            string str = new StreamReader(s).ReadToEnd();

            s.Close();
            s.Dispose();

            return str;
        }

        private static Stream ReadStream(string path)
        {
            Stream s = null;

            try
            {
                s = new System.IO.FileStream(path, System.IO.FileMode.Open, FileAccess.Read);
            }
            catch (Exception e)
            {
                LogWriter.WriteLine = e.Message;
            }

            return s;
        }
        private static Stream UnpackStream(string uri)
        {
            uri = uri.Replace("\\", "/");
            
            string package = uri.Substring(0, uri.IndexOf("/"));
            string file = uri.Substring(uri.IndexOf("/"));
            
            Stream s = new MemoryStream();

            //LogWriter.WriteLine = "UnpackStream(" + uri + ")";

            if (!File.Exists(package + ".xep"))
                return null;

            using (ZipPackage zip = (ZipPackage)ZipPackage.Open(package + ".xep", FileMode.Open, FileAccess.Read))
            {
                zip.GetPart(new Uri(file, UriKind.Relative)).GetStream().CopyTo(s);
            }

            s.Position = 0;

            return s;
        }
    }
}
